package com.pingan.haofang.searchcloud.common.rpc;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

/**
 * RPC接口
 * 
 * @author LUYI374
 * @date 2017年5月11日
 * @since 1.0.0
 */
public class RPCFilter implements Filter {

    private static final String ENCODING = "UTF-8";
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(), ENCODING));

        String content = "";
        String temp = null;
        while ((temp = reader.readLine()) != null) {
            content += temp;
        }

        RPCResponse<Object> rpcResponse = RPC.rpcInvoke(content);
        response.setCharacterEncoding(ENCODING);
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(rpcResponse));
    }

    @Override
    public void destroy() {
    }

}
